<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="search">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">
          <el-form-item label="" prop="userId">
            <el-input v-model="queryParams.userId" placeholder="请输入userId" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="" prop="firstName">
            <el-input v-model="queryParams.firstName" placeholder="请输入firstName" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="" prop="lastName">
            <el-input v-model="queryParams.lastName" placeholder="请输入lastName" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="" prop="userName">
            <el-input v-model="queryParams.userName" placeholder="请输入userName" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="" prop="address">
            <el-input v-model="queryParams.address" placeholder="请输入address" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item prop="isPremium">
            <el-select v-model="queryParams.isPremium" placeholder="请选择isPremium" clearable style="width: 240px">
              <el-option
                v-for="dict in sys_yes_no_number"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="" prop="inviteUserId">
            <el-input v-model="queryParams.inviteUserId" placeholder="请输入inviteUserId" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="交换货币" prop="currencyOfExchange">
            <el-input
              v-model="queryParams.currencyOfExchange"
              placeholder="请输入交换货币"
              clearable
              style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['mushcoin:userInfo:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['mushcoin:userInfo:export']" type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="userInfoList" @selection-change="handleSelectionChange" @sort-change="handleSortChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="true" label="id" align="center" prop="id" sortable="custom" :sort-orders="['ascending', 'descending']" />
        <el-table-column label="userId" align="center" prop="userId" />
        <el-table-column label="firstName" align="center" prop="firstName" :show-overflow-tooltip='true' />
        <el-table-column label="lastName" align="center" prop="lastName" :show-overflow-tooltip='true' />
        <el-table-column label="userName" align="center" prop="userName" :show-overflow-tooltip='true' />
        <el-table-column label="isPremium" align="center" prop="isPremium" sortable="custom" :sort-orders="['ascending', 'descending']" />
        <el-table-column label="isPremiumTg" align="center" prop="isPremiumTg" sortable="custom" :sort-orders="['ascending', 'descending']" />
        <el-table-column label="countryCode" align="center" prop="countryCode" sortable="custom" :sort-orders="['ascending', 'descending']" />
        <el-table-column label="金币" align="center" prop="gold" :show-overflow-tooltip='true' />
        <el-table-column label="钻石" align="center" prop="diamond" :show-overflow-tooltip='true' />
        <!--<el-table-column label="六芒星币" align="center" prop="rankCoin" />-->
        <el-table-column label="游戏Mushcoin" align="center" prop="mushcoin" sortable="custom" :sort-orders="['ascending', 'descending']" />
        <el-table-column label="推广Mushcoin" align="center" prop="inviteRewardsTotal" sortable="custom" :sort-orders="['ascending', 'descending']" />
        <el-table-column label="AllMushcoin" align="center" prop="allMushcoin" sortable="custom" :sort-orders="['ascending', 'descending']" />
        <el-table-column label="推荐人ID" align="center" prop="inviteUserId" />
        <el-table-column label="tonAddress" align="center" prop="address" :show-overflow-tooltip='true'/>
        <el-table-column label="邀请用户数量" align="center" prop="inviteUserCount" sortable="custom" :sort-orders="['ascending', 'descending']" />
        <el-table-column label="存档次数" align="center" prop="saveGameCount" sortable="custom" :sort-orders="['ascending', 'descending']" />
        <el-table-column label="IP" align="center" prop="ipAddress" :show-overflow-tooltip='true' />
        <el-table-column label="IP名称" align="center" prop="ipAddressName" :show-overflow-tooltip='true' />
        <el-table-column label="设备" align="center" prop="mobileDeviceName" :show-overflow-tooltip='true' sortable="custom" :sort-orders="['ascending', 'descending']" />
        <el-table-column label="VIP有效时间" align="center" prop="vipEndTime" width="180" sortable="custom" :sort-orders="['ascending', 'descending']">
          <template #default="scope">
            <span>{{ parseTime(scope.row.vipEndTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建日期" align="center" prop="createTime" width="180" sortable="custom" :sort-orders="['ascending', 'descending']">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="登录日期" align="center" prop="updateTime" width="180" sortable="custom" :sort-orders="['ascending', 'descending']" >
          <template #default="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['mushcoin:userInfo:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
<!--            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['mushcoin:userInfo:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>-->
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改TG用户对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="1000px" append-to-body>
      <el-form ref="userInfoFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="firstName" prop="firstName">
              <el-input v-model="form.firstName" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="lastName" prop="lastName">
              <el-input v-model="form.lastName" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="userName" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="是否会员" prop="isPremium">
              <el-radio-group v-model="form.isPremium">
                <el-radio v-for="dict in is_premium_dict" :key="dict.value" :label="parseInt(dict.value)" >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="会员VIP到期时间" prop="vipEndTime">
              <el-date-picker clearable
                              v-model="form.vipEndTime"
                              type="datetime"
                              value-format="YYYY-MM-DD HH:mm:ss"
                              placeholder="请选择">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="交换货币" prop="currencyOfExchange">
              <el-input v-model="form.currencyOfExchange" placeholder="请输入交换货币" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload">
          <i-ep-upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />
              是否更新已经存在的TG用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板 </el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { listUserInfo, getUserInfo, delUserInfo, addUserInfo, updateUserInfo } from '@/api/mushcoin/userInfo';
import { UserInfoVO, UserInfoQuery, UserInfoForm } from '@/api/mushcoin/userInfo/types';
import { globalHeaders } from '@/utils/request';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_yes_no_number, is_premium_dict } = toRefs<any>(proxy?.useDict('sys_yes_no_number', 'is_premium_dict'));
// 表格数据
const userInfoList = ref<UserInfoVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
// 选中数组
const ids = ref<Array<string | number>>([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 总条数
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const userInfoFormRef = ref<ElFormInstance>();
const uploadRef = ref<ElUploadInstance>();

/*** 导入参数 */
const upload = reactive<ImportOption>({
  // 是否显示弹出层（导入）
  open: false,
  // 弹出层标题（导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 1,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/mushcoin/userInfo/importData'
});

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: UserInfoForm = {
  id: undefined,
  userId: undefined,
  firstName: undefined,
  lastName: undefined,
  userName: undefined,
  isPremium: undefined,
  vipEndTime: undefined
};
// 默认排序
const defaultSort = ref<any>({ prop: 'createTime', order: 'descending' });
const data = reactive<PageData<UserInfoForm, UserInfoQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 50,
    userId: undefined,
    firstName: undefined,
    lastName: undefined,
    userName: undefined,
    isPremium: undefined,
    vipEndTime: undefined,
    mushcoin: undefined,
    inviteUserId: undefined,
    inviteRewardsTotal: undefined,
    currencyOfExchange: undefined,
    orderByColumn: defaultSort.value.prop,
    isAsc: defaultSort.value.order,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询TG用户列表 */
const getList = async () => {
  loading.value = true;
  const res = await listUserInfo(queryParams.value);
  userInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  userInfoFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 排序触发事件(my) */
/*const handleSortChange = ({ column, prop, order }) => {
  if (order === 'ascending') {
    queryParams.value.isAsc = 'asc';
  } else if (order === 'descending') {
    queryParams.value.isAsc = 'desc';
  }
  queryParams.value.orderByColumn = prop;
  queryParams.value.pageNum = 1; // 重置为第一页
  getList();
};*/

const handleSortChange = (column: any) => {
  queryParams.value.orderByColumn = column.prop;
  queryParams.value.isAsc = column.order;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: UserInfoVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = false;
  dialog.title = '添加TG用户';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: UserInfoVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getUserInfo(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改TG用户';
};

/** 提交按钮 */
const submitForm = () => {
  userInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateUserInfo(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addUserInfo(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: UserInfoVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除TG用户编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delUserInfo(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'mushcoin/userInfo/export',
    {
      ...queryParams.value
    },
    `userInfo_${new Date().getTime()}.xlsx`
  );
};

/** 导入按钮操作 */
const handleImport = () => {
  upload.title = 'TG用户导入';
  upload.open = true;
};

/** 下载模板操作 */
const importTemplate = () => {
  proxy?.download('mushcoin/userInfo/importTemplate', {}, `userInfo_template.xlsx`);
};

/**文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: UploadFile) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);
  ElMessageBox.alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', {
    dangerouslyUseHTMLString: true
  });
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value?.submit();
}

onMounted(() => {
  getList();
});
</script>
